package com.wy.navigator;

import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;

public class SqlMapXmlLineMarkerProvider extends RelatedItemLineMarkerProvider {

    // 使用常量集合优化标签判断
    private static final Set<String> SQL_OPERATION_TAGS = Set.of("select", "insert", "update", "delete");

    @Override
    protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo<?>> result) {
        // 只处理 XmlTag 元素
        if (!(element instanceof XmlTag) && element.getChildren() != null) {
            return;
        }

        XmlTag tag = (XmlTag) element;

        // 检查是否为SQL操作标签（使用常量集合优化）
        if (!SQL_OPERATION_TAGS.contains(tag.getName())) {
            return;
        }

        XmlFile xmlFile = (XmlFile) tag.getContainingFile();

        // 检查是否为 SQL Map 文件
        if (!JSearchUtils.isSqlMapFile(xmlFile)) {
            return;
        }

        var project = element.getProject();

        // 提取命名空间和操作标签列表
        var pair = JSearchUtils.getSqlMapNamespaceAndOps(xmlFile);
        if (pair == null) return;
        String namespace = pair.first;
        List<XmlTag> ops = pair.second;

        // 处理当前操作标签
        if (ops.contains(tag)) {
            XmlAttribute idAttr = JSearchUtils.getIdAttribute(tag);
            if (idAttr == null) return;
            String id = idAttr.getValue();
            if (id == null || id.isEmpty()) return;

            // 生成缓存键（namespace.id）
            String xmlKey = namespace + "." + id;

            List<PsiClass> daoImplClasses = JSearchUtils.findClassesExtendingByName(project, Arrays.asList(Constants.DAO_IMPL_CLASS_NAME, "FacadeImpl", "DAOImpl"));
            List<PsiMethod> methods = JSearchUtils.findMethodsUsingNamespaceId(project, daoImplClasses, namespace, id);


            // 3. 构建跳转标记（确保有有效方法）
            if (methods != null && !methods.isEmpty()) {
                NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(JIcons.ToJava)
                        .setTooltipText("跳转到使用 " + xmlKey + " 的 Java 方法")
                        .setTargets(methods) // 取第一个匹配方法
                        .setAlignment(GutterIconRenderer.Alignment.LEFT);

                result.add(builder.createLineMarkerInfo(tag));

            }

        }
    }
}